import axios from 'axios'
import { getToken } from '@/utils/publicUtils/auth'

const mimeMap = {
  xls: 'application/vnd.ms-excel',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  doc: 'application/msword',
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  ppt: 'application/vnd.ms-powerpoint',
  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  zip: 'application/zip',
  file: 'application/json;charset=UTF-8'
}

const baseUrl = process.env.VUE_APP_BASE_API

/**
 * @description:下载文件（get请求）
 * @Author: baoxuhui
 * @param {*} urls//请求路径
 * @param {*} query //入参
 * @param {*} fileName//下载名称 例如： a.docx
 * @return {*}
 */
export function getDownLoadFile(urls, query, fileName) {
  var url = baseUrl + urls
  axios({
    method: 'get',
    url: url,
    params: query,
    responseType: 'blob',
    headers: { 'x-auth-token': getToken() }
  }).then(res => {
    resolveBlob1(res, fileName)
  })
}
/**
 * @description:下载文件（post请求）
 * @Author: baoxuhui
 * @param {*} urls//请求路径
 * @param {*} query //入参
 * @param {*} fileName//下载名称 例如： a.docx
 * @return {*}
 */
export function postDownLoadFile(urls, fileName, data) {
  var url = baseUrl + urls
  axios({
    method: 'post',
    url: url,
    responseType: 'blob',
    data: data,
    headers: { 'x-auth-token': getToken() }
  }).then(res => {
    resolveBlob1(res, fileName)
  })
}

/**
 * @description:下载zip文件格（get请求）解析内容
 * @Author: baoxuhui
 * @param {*} urls//请求路径
 * @return {*}
 */
export function getDownLoadZip(urls) {
  var url = baseUrl + urls
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    // headers: {'Authorization': 'Bearer ' + getToken()}
    headers: { 'x-auth-token': getToken() }
  }).then(res => {
    resolveBlob(res, mimeMap.zip)
  })
}
/**
 * @description:下载zip文件格（get请求）不解析里面的内容
 * @Author: baoxuhui
 * @param {*} urls//请求路径
 * @param {*} fileName//下载名称 例如： a.docx
 * @return {*}
 */
export function getDownLoadZips(urls, filename) {
  var url = baseUrl + urls
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: { 'x-auth-token': getToken() }
  }).then(res => {
    resolveBlob2(res, filename.zip)
  })
}

// 不定文件后缀 从header 中取值
export function downLoadFileOther(str, param) {
  var url = baseUrl + str
  axios({
    method: 'get',
    url: url,
    params: param,
    responseType: 'blob',
    headers: {
      'x-auth-token': getToken()
    }
  }).then(res => {
    // 取 fileName
    const contentDisposition = decodeURI(res.headers['content-disposition'])
    const result = contentDisposition.split('filename=')
    const fileName = result[1]

    // fileName
    resolveBlob1(res, fileName)
  })
}

// a 标签下载 转blob 下载
export function downFileBlobATag(row) {
  var url = ''
  var path = row.annexPath ? row.annexPath : row.url
  if (path.includes(process.env.VUE_APP_PREVIOUS_DATA_API_NAME)) {
    url = process.env.VUE_APP_PREVIOUS_DATA_API + path.slice(process.env.VUE_APP_PREVIOUS_DATA_API_NAME.length + 4)
  } else {
    url = row.annexPath ? row.annexPath : row.url
  }
  axios({
    method: 'get',
    url: url,
    responseType: 'blob',
    headers: {
      'x-auth-token': getToken(),
      'tenant-id': localStorage.getItem('tenantId'),
      'Access-Control-Allow-Origin': '*'
    }
  }).then(res => {
    console.log('---------', res)
    const aLink = document.createElement('a')
    var blob = new Blob([res.data], { type: res.data.type })
    aLink.href = URL.createObjectURL(blob)
    aLink.setAttribute('download', row.annexName ? row.annexName : row.name) // 设置下载文件名称
    document.body.appendChild(aLink)
    aLink.click()
  })
}

// a 标签下载 直接路径下载
export function downFileATag(row){
  const aLink = document.createElement('a')
  var path = row.annexPath ? row.annexPath : row.url
  aLink.href = path
  aLink.setAttribute('download', row.annexName ? row.annexName : row.name) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {*} mimeType MIME类型
 */
export function resolveBlob1(res, fileName, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

/**
 * 解析blob响应内容并下载
 * @param {*} res blob响应内容
 * @param {*} mimeType MIME类型
 */
export function resolveBlob(res, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  var fileName = result[1]
  fileName = fileName.replace(/\"/g, '')
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}

export function resolveBlob2(res, fileName, mimeType) {
  const aLink = document.createElement('a')
  var blob = new Blob([res.data], { type: mimeType })
  // //从response的headers中获取filename, 后端response.setHeader("Content-disposition", "attachment; filename=xxxx.docx") 设置的文件名;
  var patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
  var contentDisposition = decodeURI(res.headers['content-disposition'])
  var result = patt.exec(contentDisposition)
  aLink.href = URL.createObjectURL(blob)
  aLink.setAttribute('download', fileName) // 设置下载文件名称
  document.body.appendChild(aLink)
  aLink.click()
  document.body.appendChild(aLink)
}
